<template>
  <div class="script-action">
    <div
      class="script-row"
      v-for="(action, index) in actions"
      :key="action.key"
    >
      <cg-input
        :modelValue="action.content"
        @update:modelValue="(value) => setScriptValue(index, value)"
      ></cg-input>
      <cg-button icon="close" @click="removeScript(index)"></cg-button>
    </div>
    <div class="script-button">
      <cg-button @click="addScript">添加命令</cg-button>
      <!-- <cg-button>添加动作</cg-button> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import _ from "lodash";
import { ref, onMounted, watch, toRaw } from "vue";

defineOptions({
  name: "script-action",
});

const emit = defineEmits(["update:modelValue"]);

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  options: {
    type: Array,
    default: () => [],
  },
});

// 脚本动作
const actions = ref([]);

const buildEmptyScript = () => {
  return {
    type: 0, // 类型，0为文本命令 1为动作命令
    content: "",
  };
};

const addScript = () => {
  actions.value.push(buildEmptyScript());
};

const removeScript = (index) => {
  actions.value.splice(index, 1);
};

const setScriptValue = (index, value) => {
  actions.value[index].content = value;
  pushValue();
};

const pushValue = _.debounce(
  () => {
    let data = toRaw(
      actions.value.map((it) => {
        delete it.key;
        return toRaw(it);
      })
    );
    emit("update:modelValue", data);
  },
  100,
  { trailing: true, leading: false }
);

onMounted(() => {
  actions.value = props.modelValue;
});

watch(
  () => props.modelValue,
  () => {
    actions.value = props.modelValue;
  }
);
</script>

<style lang="scss">
.script-action {
  .script-row {
    display: flex;
    flex-direction: row;
    margin-bottom: 0.24rem;

    .cg-input {
      flex: 1;
    }

    .cg-button {
      flex: 0;
    }
  }

  .script-button {
    .cg-button {
      display: block;
    }
  }
}
</style>
